// 表格的导出
import * as XLSX from 'xlsx' // Vue3 版本
/*
    * @description:
    * @param {Object} json 服务端发过来的数据
    * @param {String} name 导出Excel文件名字
   
    * @param {String} titleArr 导出Excel表头
   
    * @param {String} sheetName 导出sheetName名字
    * @return:
    */
function exportExcel(json:any[], name:string, titleArr:string[], sheetName:string) {
  
  const list = json.map(item => {
    const obj = {}
    for (const k in item) {
      // @ts-ignore
      if (titleArr[k]) {
        // @ts-ignore
        obj[titleArr[k]] = item[k]
      } 
    }
    return obj
  })
  console.log(list);
  
  // 创建工作表
  const data = XLSX.utils.json_to_sheet(list)
  // 创建工作簿
  const wb = XLSX.utils.book_new()
  // 将工作表放入工作簿中
  XLSX.utils.book_append_sheet(wb, data, 'data')
  // 生成文件并下载
  XLSX.writeFile(wb, name+'.xlsx')
}
// 表格的导出
const exportExcelRef = (name: string,columns:any[],data:Columns[]) => {
  const heardNameArr: any = {}
  columns.map(val => {
    if (!(val.type === 'actionBtns')) {
      console.log( heardNameArr);
      
      heardNameArr[val.dataIndex] = val.title
    }
  })
  console.log(heardNameArr);
  
  const tData: any[] = []
  
  for (let j of data) {
    let callback: any
    const objKey = {}
    columns.map(val => {
      if (val.type === 'function') {
        callback = val.callback
        // @ts-ignore
        objKey[val.dataIndex] = callback(j)
      } else {
        // @ts-ignore
        objKey[val.dataIndex] = j[val.dataIndex]  
      }
    })
    tData.push(objKey)
  }
  exportExcel(tData, name, heardNameArr, 'sheetName')
}
// eslint-disable-next-line import/no-anonymous-default-export
export default {
  exportExcel,
  exportExcelRef
}